using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

using SpeechLib;

namespace SpellingQuiz
{
	/// <summary>
	/// Summary description for Utilities.
	/// </summary>
	public class Utilities
	{
        private static SpVoice objSpeech = new SpVoice();

        private static List<SpellingUser> data;
        private static SpellingUser currentUser;

		private Utilities()
		{
		}

        public static List<SpellingUser> GetData()
        {
            return data;
        }

        public static void SetCurrentUser(SpellingUser user)
        {
            currentUser = user;
        }

        public static SpellingUser GetCurrentUser()
        {
            return currentUser;
        }

		public static void Speak( string tts )
		{
			
			objSpeech.Speak(tts, SpeechVoiceSpeakFlags.SVSFlagsAsync);
			//objSpeech.WaitUntilDone(9999); 
		}

		public static void LoadData()
		{
            List<SpellingUser>  users = null;

			TextReader r = null;
			try
			{
                string fn = Path.Combine(System.Environment.CurrentDirectory, "spellingquiz.xml");
                
                // Make sure the file is there
				if( File.Exists( fn ) )
				{
                    XmlSerializer s = new XmlSerializer(typeof(List<SpellingUser>), new System.Type[] { typeof(SpellingEntry) });
                    r = new StreamReader(fn);
                    users = (List<SpellingUser>)s.Deserialize(r);
				}
				else
				{
					System.Windows.Forms.MessageBox.Show( "No words found.  Make sure you enter your spelling list with the \"Word List\" button.", "First time?");
				}
			}
			catch( Exception ex )
			{
				System.Windows.Forms.MessageBox.Show( "Error reading the words list.  You will need to use the \"Word List\" button to add them.\nError: " + ex.Message, "Error!" );
			}
			finally
			{
				if( r != null ) r.Close();

				if( users == null )
				{
					users = new List<SpellingUser>();
				}
			}

			data = users;
		}

		public static void SaveData(  )
		{
			//Save words
			if( data != null )
			{
                XmlSerializer s = new XmlSerializer(typeof(List<SpellingUser>), new System.Type[] { typeof(SpellingEntry) });
                string fn = Path.Combine(System.Environment.CurrentDirectory, "spellingquiz.xml");
				TextWriter w = new StreamWriter( fn );
				s.Serialize( w, data );
				w.Close();
			}
		}
	}
}
